async function fetchWorkflows() {
    try {
        const response = await fetch('/_/workflows/running');
        if (!response.ok) {
            throw new Error('获取工作流数据失败');
        }
        return await response.json();
    } catch (error) {
        console.error('Error fetching workflows:', error);
        return [];
    }
}
async function fetchTasks() {
    try {
        const response = await fetch('/_/tasks/list');
        if (!response.ok) {
            throw new Error('获取任务数据失败');
        }
        return await response.json();
    } catch (error) {
        console.error('Error fetching tasks:', error);
        return [];
    }
}
async function deleteWorkflow(port) {
    try {
        const response = await fetch(`/_/workflows/running/${port}`, {
            method: 'DELETE'
        });
        if (!response.ok) {
            throw new Error('删除工作流失败');
        }
        return await response.json();
    } catch (error) {
        console.error('Error deleting workflow:', error);
        return { success: false, message: error.message };
    }
}
async function terminateTask(taskId) {
    try {
        const response = await fetch(`/_/tasks/${taskId}/terminate`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        });
        
        if (!response.ok) {
            throw new Error('终止任务失败');
        }
        
        const result = await response.json();
        return result;
    } catch (error) {
        console.error(`终止任务 ${taskId} 失败:`, error);
        return { success: false, message: error.message };
    }
}
function manageWorkflows() {
    const container = document.getElementById('workflows-container');
    let activeWorkflows = new Set();
    const refreshButton = document.createElement('button');
    let pollInterval;
    refreshButton.className = 'refresh-btn';
    refreshButton.innerHTML = '刷新';
    const workflowPollingInterval = 1000;
    container.parentElement.style.position = 'relative';
    container.parentElement.appendChild(refreshButton);
    const style = document.createElement('style');
    style.textContent = `
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        .refresh-btn.refreshing {
            pointer-events: none;
            opacity: 0.7;
        }
        .refresh-btn.refreshing::after {
            content: '⟳';
            display: inline-block;
            margin-left: 5px;
            animation: spin 1s linear infinite;
        }
    `;
    document.head.appendChild(style);
    async function refresh() {
        refreshButton.classList.add('refreshing');
        try {
            const workflowsData = await fetchWorkflows();
            clearInterval(pollInterval);
            const workflows = Object.entries(workflowsData.running_workflows).map(([port, workflow]) => ({
                port,
                ...workflow
            }));
            container.innerHTML = workflows.map(renderWorkflowCard).join('');
            workflows.forEach(setupWorkflowEvents);
            activeWorkflows = new Set(workflows.filter(w => w.status !== "Finished" && w.status !== "Failed").map(w => w.port));
            if (activeWorkflows.size > 0) {
                pollInterval = setInterval(pollWorkflows, workflowPollingInterval);
            }
        } catch (error) {
            console.error('刷新工作流失败:', error);
        } finally {
            refreshButton.classList.remove('refreshing');
        }
    }
    refreshButton.addEventListener('click', refresh);
    async function updateWorkflowUI(workflow) {
        const progressBar = document.getElementById(`workflow-progress-${workflow.port}`);
        if (!progressBar) return;
        const progressFill = progressBar.querySelector('.progress-fill');
        const progressText = document.getElementById(`workflow-progress-text-${workflow.port}`);
        const statusIcon = document.getElementById(`workflow-status-${workflow.port}`);
        const statusText = document.getElementById(`workflow-status-text-${workflow.port}`);
        const deleteBtn = document.getElementById(`delete-${workflow.port}`);
        const resultBtn = document.getElementById(`result-${workflow.port}`);
        const detailsDiv = document.getElementById(`workflow-details-${workflow.port}`);
        const progress = workflow.progress_percentage || 0;
        const status = workflow.status || 'Running';
        if (status === 'Finished') {
            statusIcon.className = 'status-icon completed';
            statusIcon.innerHTML = '✓';
            statusText.textContent = '已完成';
            // 更新进度条
            progressFill.style.width = '100%';
            progressText.textContent = '100%';
            if (deleteBtn) {
                deleteBtn.disabled = false;
                deleteBtn.textContent = '删除';
            }
            if (resultBtn) {
                resultBtn.style.display = 'inline-block';
            }
            activeWorkflows.delete(workflow.port);
        } else if (status === 'Failed') {
            statusIcon.className = 'status-icon error';
            statusIcon.innerHTML = '✕';
            statusText.textContent = '已失败';
            if (deleteBtn) {
                deleteBtn.disabled = false;
                deleteBtn.textContent = '删除';
            }
            if (resultBtn) {
                resultBtn.style.display = 'none';
            }
            if (detailsDiv) {
                const errorDiv = detailsDiv.querySelector('.error-message');
                if (errorDiv) {
                    errorDiv.textContent = `错误：${workflow.error_message}`;
                }
            }
            activeWorkflows.delete(workflow.port);
        } else {
            statusIcon.className = 'status-icon in-progress';
            statusIcon.innerHTML = '⟳';
            statusText.textContent = '运行中...';
            if (deleteBtn) {
                deleteBtn.disabled = true;
                deleteBtn.textContent = '运行中';
            }
            if (resultBtn) {
                resultBtn.style.display = 'none';
            }
            // 更新进度条
            progressFill.style.width = `${progress}%`;
            progressText.textContent = `${Math.round(progress)}%`;
        }
    }
    function renderWorkflowCard(workflow) {
        return `
            <div class="workflow-card" id="workflow-${workflow.port}">
                <div class="workflow-header">
                    <div class="workflow-info">
                        <div class="workflow-name">
                            <span class="name-value">${workflow.name}</span>
                        </div>
                        <div class="workflow-status-info">
                            <span class="status-label">状态：</span>
                            <span class="status-value" id="workflow-status-text-${workflow.port}">待渲染...</span>
                            <i class="status-icon" id="workflow-status-${workflow.port}"></i>
                        </div>
                    </div>
                    <div class="workflow-actions">
                        <button class="result-btn" id="result-${workflow.port}" data-port="${workflow.port}" style="display: none;">获取结果</button>
                        <button class="delete-btn" id="delete-${workflow.port}" data-port="${workflow.port}">删除</button>
                        <button class="expand-btn" data-port="${workflow.port}">
                            <i class="expand-icon">▼</i>
                        </button>
                    </div>
                </div>
                <div class="progress-container">
                    <div class="progress-bar" id="workflow-progress-${workflow.port}">
                        <div class="progress-fill" style="width: 0%"></div>
                    </div>
                    <div class="progress-info">
                        <span class="progress-text" id="workflow-progress-text-${workflow.port}">...</span>
                    </div>
                </div>
                <div class="workflow-details" id="workflow-details-${workflow.port}" style="display: none;">
                    <div class="error-message">没有错误信息</div>
                    <div class="result-content" id="result-content-${workflow.port}" style="display: none;"></div>
                </div>
            </div>
        `;
    }
    function setupWorkflowEvents(workflow) {
        const expandBtn = document.querySelector(`.expand-btn[data-port="${workflow.port}"]`);
        const detailsDiv = document.getElementById(`workflow-details-${workflow.port}`);
        const expandIcon = expandBtn.querySelector('.expand-icon');
        const resultBtn = document.getElementById(`result-${workflow.port}`);

        expandBtn.addEventListener('click', () => {
            const isExpanded = detailsDiv.style.display !== 'none';
            detailsDiv.style.display = isExpanded ? 'none' : 'block';
            expandIcon.style.transform = isExpanded ? 'rotate(0deg)' : 'rotate(180deg)';
        });

        if (resultBtn) {
            resultBtn.addEventListener('click', async () => {
                try {
                    const response = await fetch(`/_/workflows/running/${workflow.port}/result`);
                    if (!response.ok) {
                        throw new Error('获取结果失败');
                    }
                    const result = await response.json();
                    const resultContent = document.getElementById(`result-content-${workflow.port}`);
                    resultContent.style.display = 'block';
                    resultContent.textContent = JSON.stringify(result, null, 2);
                    detailsDiv.style.display = 'block';
                    expandIcon.style.transform = 'rotate(180deg)';
                } catch (error) {
                    console.error('获取工作流结果失败:', error);
                    alert('获取工作流结果失败：' + error.message);
                }
            });
        }

        const deleteBtn = document.getElementById(`delete-${workflow.port}`);
        if (deleteBtn) {
            deleteBtn.addEventListener('click', async (e) => {
                e.preventDefault();
                const port = e.target.getAttribute('data-port');
                if (!port) throw Error("port not found");
                e.target.disabled = true;
                e.target.textContent = '删除中...';
                await deleteWorkflow(port);
                await new Promise(resolve => setTimeout(resolve, 500));
                await refresh();
            });
        }
    }
    async function pollWorkflows() {
        try {
            let data = await fetchWorkflows();
            data = data.running_workflows;
            for (const [port, progressData] of Object.entries(data)) {
                const workflow = { port, ...progressData };
                await updateWorkflowUI(workflow);
            }
            if (activeWorkflows.size === 0) {
                clearInterval(pollInterval);
            }
        } catch (error) {
            console.error('获取工作流进度失败:', error);
            for (const port of activeWorkflows) {
                const statusIcon = document.getElementById(`workflow-status-${port}`);
                const deleteBtn = document.getElementById(`delete-${port}`);
                if (statusIcon) {
                    statusIcon.className = 'status-icon error';
                    statusIcon.innerHTML = '⚠';
                }
                if (deleteBtn) {
                    deleteBtn.disabled = true;
                    deleteBtn.textContent = '连接失败';
                }
            }
            activeWorkflows.clear();
        }
    }
    async function render() {
        const workflowsData = await fetchWorkflows();
        const workflows = Object.entries(workflowsData.running_workflows).map(([port, workflow]) => ({
            port,
            ...workflow
        }));
        container.innerHTML = workflows.map(renderWorkflowCard).join('');
        workflows.forEach(setupWorkflowEvents);
        activeWorkflows = new Set(workflows.map(w => w.port));
        if (activeWorkflows.size > 0) {
            pollInterval = setInterval(pollWorkflows, workflowPollingInterval);
        }
    }
    return { render, refresh };
}
function renderTasks(tasksData) {
    const container = document.getElementById('tasks-container');
    container.innerHTML = tasksData.map(task => `
        <div class="task-card" id="task-${task.key}">
            <div class="task-header">
                <p><b>${task.service_name}: ${task.name}</b></p>
                <p>started at ${new Date(task.created_at * 1000).toLocaleString()}</p>
                <div class="task-controls">
                    <div class="task-status">
                        <i class="status-icon" id="status-${task.key}"></i>
                    </div>
                    <button class="terminate-btn" id="terminate-${task.key}" data-task-id="${task.id}">中止</button>
                </div>
            </div>
            <div class="progress-container">
                <div class="progress-bar" id="progress-${task.key}">
                    <div class="progress-fill" style="width: 0%"></div>
                </div>
                <span class="progress-text" id="progress-text-${task.key}">0%</span>
            </div>
        </div>
    `).join('');
    tasksData.forEach(task => {
        const terminateBtn = document.getElementById(`terminate-${task.key}`);
        if (terminateBtn) {
            terminateBtn.addEventListener('click', async (e) => {
                e.preventDefault();
                const taskId = e.target.getAttribute('data-task-id');
                if (!taskId) throw Error("task id not found");
                e.target.disabled = true;
                e.target.textContent = '中止中...';
                const result = await terminateTask(taskId);
                if (result.success) {
                    e.target.textContent = '已中止';
                    const statusIcon = document.getElementById(`status-${task.key}`);
                    statusIcon.className = 'status-icon error';
                    statusIcon.innerHTML = '✕';
                } else {
                    e.target.disabled = false;
                    e.target.textContent = '中止';
                    alert(`终止任务失败: ${result.message}`);
                }
            });
        }

        startTaskProgressPolling(task);
    });
}
function taskResultButton(task_id) {
    const resultBtn = document.createElement('button');
    resultBtn.textContent = '获取结果';
    resultBtn.className = 'result-btn';
    resultBtn.style.marginLeft = '10px';
    resultBtn.style.padding = '5px 10px';
    resultBtn.style.backgroundColor = '#4CAF50';
    resultBtn.style.color = 'white';
    resultBtn.style.border = 'none';
    resultBtn.style.borderRadius = '4px';
    resultBtn.style.cursor = 'pointer';

    // 创建可折叠的结果区域
    const taskCard = document.getElementById(`task-${task_id}`);
    const detailsDiv = document.createElement('div');
    detailsDiv.className = 'task-details';
    detailsDiv.style.display = 'none';
    detailsDiv.style.marginTop = '10px';
    detailsDiv.style.padding = '10px';
    detailsDiv.style.backgroundColor = '#f5f5f5';
    detailsDiv.style.borderRadius = '4px';

    const resultContent = document.createElement('div');
    resultContent.className = 'result-content';
    detailsDiv.appendChild(resultContent);
    taskCard.appendChild(detailsDiv);

    resultBtn.addEventListener('click', async () => {
        try {
            const resultResponse = await fetch(`/_/tasks/${task_id}/result`);
            if (!resultResponse.ok) {
                alert(`获取结果失败: ${resultResponse.text()}`);
                return;
            }
            const resultData = await resultResponse.json();
            console.log(resultData);
            resultContent.textContent = JSON.stringify(resultData, null, 2);
            detailsDiv.style.display = detailsDiv.style.display === 'none' ? 'block' : 'none';
        } catch (error) {
            alert(`获取结果失败: ${error.message}`);
        }
    });
    return resultBtn;
}
function startTaskProgressPolling(task) {
    const taskPollingInterval = 1000;
    console.log('startTaskProgressPolling', task);
    const progressBar = document.getElementById(`progress-${task.key}`);
    const progressFill = progressBar.querySelector('.progress-fill');
    const progressText = document.getElementById(`progress-text-${task.key}`);
    const statusIcon = document.getElementById(`status-${task.key}`);
    const terminateBtn = document.getElementById(`terminate-${task.key}`);
    const pollInterval = setInterval(async () => {
        try {
            const local_stream_addr = '/_/tasks/' + task.id + '/progress';
            const response = await fetch(`${local_stream_addr}`);
            if (!response.ok) {
                throw new Error('获取进度失败');
            }
            const data = await response.json();
            const progress = data.progress_percentage || 0;
            const status = data.status || 'Running';
            progressFill.style.width = `${progress}%`;
            progressText.textContent = `${Math.round(progress)}%`;
            if (status === 'Completed' || status === 'ResultReceived') {
                statusIcon.className = 'status-icon completed';
                statusIcon.innerHTML = '✓';
                if (terminateBtn) {
                    terminateBtn.disabled = true;
                    terminateBtn.textContent = '已完成';
                }
                clearInterval(pollInterval);
                let resultBtn = taskResultButton(task.id);
                progressBar.parentElement.appendChild(resultBtn);
            } else if (status === "Stopped") {
                statusIcon.className = 'status-icon error';
                statusIcon.innerHTML = '✕';
                if (terminateBtn) {
                    terminateBtn.disabled = true;
                    terminateBtn.textContent = '已中止';
                }
                clearInterval(pollInterval);
            } else if (status === "Closed") {
                statusIcon.className = 'status-icon error';
                statusIcon.innerHTML = '✕';
                if (terminateBtn) {
                    terminateBtn.disabled = true;
                    terminateBtn.textContent = '远程连接已断开';
                }
                clearInterval(pollInterval);
            } else if (status === "Failed") {
                statusIcon.className = 'status-icon error';
                statusIcon.innerHTML = '✕';
                if (terminateBtn) {
                    terminateBtn.disabled = true;
                    terminateBtn.textContent = '任务失败';
                }
                alert(`任务失败（${data.error_message}）`);
                clearInterval(pollInterval);
            } else if (status === "FailedToGetResult") {
                statusIcon.className = 'status-icon error';
                statusIcon.innerHTML = '✕';
                if (terminateBtn) {
                    terminateBtn.disabled = true;
                    terminateBtn.textContent = '获取远程结果失败';
                }
                clearInterval(pollInterval);
            } else {
                statusIcon.className = 'status-icon in-progress';
                statusIcon.innerHTML = '⟳';
            }
        } catch (error) {
            console.error(`获取任务 ${task.key} 进度失败:`, error);
            statusIcon.className = 'status-icon error';
            statusIcon.innerHTML = '⚠';
            if (terminateBtn) {
                terminateBtn.disabled = true;
                terminateBtn.textContent = '连接失败';
            }
            clearInterval(pollInterval);
        }
    }, taskPollingInterval);
}
function initSplitPanel() {
    const container = document.querySelector('.split-container');
    const leftPane = document.querySelector('.left-pane');
    const rightPane = document.querySelector('.right-pane');
    const handle = document.querySelector('.split-handle');
    const taskContainer = document.querySelector('#tasks-container');

    const refreshButton = document.createElement('button');
    refreshButton.className = 'refresh-btn';
    refreshButton.innerHTML = '刷新';
    refreshButton.addEventListener('click', refreshTasks);
    taskContainer.parentElement.style.position = 'relative';
    taskContainer.parentElement.appendChild(refreshButton);

    let isResizing = false;
    let startX;
    let startLeftWidth;

    handle.addEventListener('mousedown', (e) => {
        isResizing = true;
        startX = e.clientX;
        startLeftWidth = leftPane.offsetWidth;
        document.body.style.cursor = 'col-resize';
        handle.classList.add('active');
    });

    document.addEventListener('mousemove', (e) => {
        if (!isResizing) return;

        const deltaX = e.clientX - startX;
        const newLeftWidth = startLeftWidth + deltaX;
        const containerWidth = container.offsetWidth;

        // 限制最小宽度为20%
        const minWidth = containerWidth * 0.2;
        const maxWidth = containerWidth * 0.8;

        if (newLeftWidth >= minWidth && newLeftWidth <= maxWidth) {
            leftPane.style.flex = 'none';
            leftPane.style.width = `${newLeftWidth}px`;
            rightPane.style.flex = '1';
        }
    });

    document.addEventListener('mouseup', () => {
        isResizing = false;
        document.body.style.cursor = 'default';
        handle.classList.remove('active');
    });
}
async function refreshTasks() {
    const task_dict = await fetchTasks();
    for (const [id, task] of Object.entries(task_dict)) {
        task_dict[id] = {
            ...task,
            key: id
        }
    }
    tasks = Object.values(task_dict)
    tasks.sort((a, b) => {
        // 首先按照状态排序：运行中的任务排在前面
        if (a.status === 'Running' && b.status !== 'Running') return -1;
        if (a.status !== 'Running' && b.status === 'Running') return 1;
        
        // 如果状态相同，则按照创建时间由晚到早排序
        return b.created_at - a.created_at;
    });
    renderTasks(tasks);
}
document.addEventListener('DOMContentLoaded', async () => {
    initSplitPanel();
    refreshTasks();    
    const workflowManager = manageWorkflows();
    await workflowManager.render();
}); 